import numpy as np

A = np.array([[0.5, 0.2, 0.3], [0.3, 0.5, 0.2], [0.2, 0.3, 0.5]])
B = np.array([[0.5, 0.5], [0.4, 0.6], [0.7, 0.3]])
Pi = np.transpose(np.array([0.2, 0.4, 0.4]))
O = [0, 1, 0]
N = len(A)
T = len(O)
M = len(B[0])

def Viterbi(A, B, Pi, O):
    delta = B[:, O[0]] * Pi
    fai = np.zeros((N, T), dtype=int)
    for t in range(1, T):
        for i in range(N):
            transfer = delta * A[:, i]
            max_index = np.argmax(transfer)
            fai[i][t] = max_index
            delta[i] = max(transfer) * B[i][O[t]]
            
    I = [0] * T
    I[-1] = np.argmax(delta)
    for i in reversed(range(T-1)):
        #这里要主要np.zeros默认数据类型是float
        I[i] = fai[I[i+1], i+1]
    
    return delta, I



delta, I = Viterbi(A, B, Pi, O)